<template>
  <div class="source-data-page">
    <div class="page-header">
      <h2>源数据管理</h2>
      <p>管理和维护原始数据资源，支持文件上传、下载和管理</p>
      <div class="header-actions">
        <a-button type="primary" @click="showUploadModal = true">
          <template #icon>📤</template>
          上传文件
        </a-button>
        <a-button type="outline" @click="refreshFileList">
          <template #icon>🔄</template>
          刷新
        </a-button>
      </div>
    </div>
    
    <div class="content-container">
      <!-- 存储桶选择 -->
      <div class="bucket-selector">
        <a-select 
          v-model="selectedBucket" 
          style="width: 200px"
          @change="handleBucketChange"
          placeholder="选择存储桶"
        >
          <a-option 
            v-for="bucket in buckets" 
            :key="bucket.name" 
            :value="bucket.name"
          >
            {{ bucket.name }}
          </a-option>
        </a-select>
        <a-button type="text" @click="showCreateBucketModal = true">
          <template #icon>➕</template>
          新建存储桶
        </a-button>
      </div>

      <!-- 文件列表 -->
      <div class="file-list-container">
        <div class="file-list-header">
          <h3>文件列表 ({{ files.length }} 个文件)</h3>
          <div class="file-actions">
            <a-input-search 
              v-model="searchKeyword"
              placeholder="搜索文件..."
              style="width: 200px"
              @search="handleSearch"
            />
          </div>
        </div>
        
        <div class="file-list" v-if="files.length > 0">
          <div 
            v-for="file in filteredFiles" 
            :key="file.name"
            class="file-item"
          >
            <div class="file-icon">
              <span v-html="getFileIcon(file.name)"></span>
            </div>
            <div class="file-info">
              <div class="file-name">{{ file.name }}</div>
              <div class="file-meta">
                <span class="file-size">{{ formatFileSize(file.size) }}</span>
                <span class="file-date">{{ formatDate(file.last_modified) }}</span>
                <span class="file-type">{{ file.content_type }}</span>
              </div>
            </div>
            <div class="file-actions">
              <a-button 
                type="text" 
                size="small"
                @click="downloadFile(file)"
                title="下载"
              >
                📥
              </a-button>
              <a-button 
                type="text" 
                size="small"
                @click="getPresignedUrl(file)"
                title="获取链接"
              >
                🔗
              </a-button>
              <a-button 
                type="text" 
                size="small"
                @click="deleteFile(file)"
                title="删除"
                status="danger"
              >
                🗑️
              </a-button>
            </div>
          </div>
        </div>
        
        <div v-else class="empty-state">
          <div class="empty-icon">📁</div>
          <h3>暂无文件</h3>
          <p>点击"上传文件"按钮开始上传文件</p>
        </div>
      </div>
    </div>

    <!-- 文件上传模态框 -->
    <a-modal 
      v-model:visible="showUploadModal"
      title="上传文件"
      @ok="handleUpload"
      @cancel="showUploadModal = false"
      :confirm-loading="uploading"
    >
      <div class="upload-container">
        <!-- 简单的文件选择 -->
        <div class="upload-area" @click="triggerFileInput">
          <input 
            ref="fileInput"
            type="file" 
            multiple 
            style="display: none"
            @change="handleFileSelect"
            accept="*/*"
          >
          <div class="upload-content">
            <div class="upload-icon">📤</div>
            <div class="upload-text">点击选择文件</div>
            <div class="upload-hint">支持多种文件格式，最大100MB</div>
          </div>
        </div>
        
        <!-- 已选择的文件列表 -->
        <div v-if="selectedFiles.length > 0" class="selected-files">
          <h4>已选择的文件 ({{ selectedFiles.length }} 个):</h4>
          <div class="file-list">
            <div 
              v-for="(file, index) in selectedFiles" 
              :key="index"
              class="selected-file-item"
            >
              <span class="file-name">{{ file.name }}</span>
              <span class="file-size">({{ formatFileSize(file.size) }})</span>
              <a-button 
                type="text" 
                size="small"
                @click="removeFile(index)"
                status="danger"
              >
                ❌
              </a-button>
            </div>
          </div>
        </div>
        
        <!-- 存储桶选择 -->
        <div class="upload-options">
          <label>选择存储桶:</label>
          <a-select 
            v-model="uploadBucket" 
            placeholder="选择存储桶"
            style="width: 100%; margin-top: 8px"
          >
            <a-option 
              v-for="bucket in buckets" 
              :key="bucket.name" 
              :value="bucket.name"
            >
              {{ bucket.name }}
            </a-option>
          </a-select>
        </div>
      </div>
    </a-modal>

    <!-- 创建存储桶模态框 -->
    <a-modal 
      v-model:visible="showCreateBucketModal"
      title="创建存储桶"
      @ok="handleCreateBucket"
      @cancel="showCreateBucketModal = false"
    >
      <a-input 
        v-model="newBucketName"
        placeholder="请输入存储桶名称"
        @press-enter="handleCreateBucket"
      />
    </a-modal>

    <!-- 预签名URL模态框 -->
    <a-modal 
      v-model:visible="showUrlModal"
      title="文件访问链接"
      @cancel="showUrlModal = false"
    >
      <div class="url-container">
        <p><strong>文件:</strong> {{ selectedFile?.name }}</p>
        <p><strong>链接:</strong></p>
        <a-input 
          v-model="presignedUrl"
          readonly
          style="margin-bottom: 10px"
        />
        <p class="url-hint">此链接7天内有效，可直接用于访问文件</p>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { Message } from '@arco-design/web-vue'

// API基础URL - 直接使用后端地址
const API_BASE_URL = 'http://localhost:5000/api'

// 响应式数据
const selectedBucket = ref('source-data')
const buckets = ref([])
const files = ref([])
const searchKeyword = ref('')
const showUploadModal = ref(false)
const showCreateBucketModal = ref(false)
const showUrlModal = ref(false)
const uploading = ref(false)
const selectedFiles = ref([])
const uploadBucket = ref('source-data')
const newBucketName = ref('')
const selectedFile = ref(null)
const presignedUrl = ref('')
const fileInput = ref(null)

// 计算属性
const filteredFiles = computed(() => {
  if (!searchKeyword.value) {
    return files.value
  }
  return files.value.filter(file => 
    file.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 文件图标映射
const getFileIcon = (fileName) => {
  const ext = fileName.split('.').pop()?.toLowerCase()
  const iconMap = {
    'pdf': '📄',
    'doc': '📝', 'docx': '📝',
    'xls': '📊', 'xlsx': '📊', 'csv': '📊',
    'ppt': '📋', 'pptx': '📋',
    'txt': '📄', 'md': '📄',
    'jpg': '🖼️', 'jpeg': '🖼️', 'png': '🖼️', 'gif': '🖼️',
    'mp4': '🎥', 'avi': '🎥', 'mov': '🎥',
    'mp3': '🎵', 'wav': '🎵',
    'zip': '📦', 'rar': '📦', '7z': '📦',
    'py': '🐍', 'js': '📜', 'html': '🌐', 'css': '🎨', 'vue': '💚',
    'json': '📋', 'xml': '📋',
    'sql': '🗄️', 'log': '📋'
  }
  return iconMap[ext] || '📄'
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// API调用函数
const apiCall = async (url, options = {}) => {
  try {
    console.log(`🌐 API调用: ${API_BASE_URL}${url}`)
    const response = await fetch(`${API_BASE_URL}${url}`, {
      mode: 'cors',
      headers: {
        'Content-Type': 'application/json',
        ...options.headers
      },
      ...options
    })
    
    const data = await response.json()
    console.log(`📡 API响应:`, data)
    
    if (!response.ok) {
      throw new Error(data.error || '请求失败')
    }
    
    return data
  } catch (error) {
    console.error('❌ API调用失败:', error)
    Message.error(error.message || '网络请求失败')
    throw error
  }
}

// 获取存储桶列表
const fetchBuckets = async () => {
  try {
    console.log('📦 获取存储桶列表...')
    const data = await apiCall('/buckets')
    buckets.value = data.buckets || []
    console.log('📦 存储桶列表:', buckets.value)
    if (buckets.value.length > 0 && !selectedBucket.value) {
      selectedBucket.value = buckets.value[0].name
    }
  } catch (error) {
    console.error('❌ 获取存储桶列表失败:', error)
  }
}

// 获取文件列表
const fetchFiles = async (bucketName) => {
  try {
    console.log(`📁 获取文件列表: ${bucketName}`)
    const data = await apiCall(`/files/${bucketName}`)
    files.value = data.files || []
    console.log(`📁 文件列表 (${files.value.length}个文件):`, files.value)
  } catch (error) {
    console.error('❌ 获取文件列表失败:', error)
    files.value = []
  }
}

// 刷新文件列表
const refreshFileList = () => {
  if (selectedBucket.value) {
    fetchFiles(selectedBucket.value)
  }
}

// 存储桶切换
const handleBucketChange = (bucketName) => {
  console.log(`🔄 切换存储桶: ${bucketName}`)
  selectedBucket.value = bucketName
  fetchFiles(bucketName)
}

// 搜索文件
const handleSearch = (value) => {
  console.log(`🔍 搜索文件: ${value}`)
  searchKeyword.value = value
}

// 文件上传相关
const triggerFileInput = () => {
  fileInput.value?.click()
}

const handleFileSelect = (event) => {
  const files = Array.from(event.target.files)
  selectedFiles.value = files
  console.log(`📝 选择了 ${files.length} 个文件:`, files.map(f => f.name))
}

const removeFile = (index) => {
  selectedFiles.value.splice(index, 1)
  console.log(`🗑️ 移除文件，剩余 ${selectedFiles.value.length} 个文件`)
}

const handleUpload = async () => {
  if (selectedFiles.value.length === 0) {
    Message.warning('请选择要上传的文件')
    return
  }
  
  console.log(`🚀 开始上传 ${selectedFiles.value.length} 个文件...`)
  uploading.value = true
  
  try {
    for (const file of selectedFiles.value) {
      const formData = new FormData()
      formData.append('file', file)
      formData.append('bucket', uploadBucket.value)
      
      console.log('📤 上传文件到:', `${API_BASE_URL}/files/upload`)
      console.log('📄 文件信息:', {
        name: file.name,
        size: file.size,
        type: file.type
      })
      
      const response = await fetch(`${API_BASE_URL}/files/upload`, {
        method: 'POST',
        mode: 'cors',
        body: formData
      })
      
      console.log('📡 上传响应状态:', response.status)
      
      if (!response.ok) {
        throw new Error(`HTTP错误: ${response.status}`)
      }
      
      const result = await response.json()
      console.log('📄 上传响应内容:', result)
      
      if (!result.success) {
        throw new Error(result.error || '上传失败')
      }
    }
    
    Message.success('文件上传成功')
    showUploadModal.value = false
    selectedFiles.value = []
    refreshFileList()
  } catch (error) {
    console.error('❌ 文件上传失败:', error)
    Message.error(`文件上传失败: ${error.message}`)
  } finally {
    uploading.value = false
  }
}

// 创建存储桶
const handleCreateBucket = async () => {
  if (!newBucketName.value.trim()) {
    Message.warning('请输入存储桶名称')
    return
  }
  
  try {
    console.log(`➕ 创建存储桶: ${newBucketName.value}`)
    await apiCall('/buckets', {
      method: 'POST',
      body: JSON.stringify({ name: newBucketName.value })
    })
    
    Message.success('存储桶创建成功')
    showCreateBucketModal.value = false
    newBucketName.value = ''
    fetchBuckets()
  } catch (error) {
    console.error('❌ 存储桶创建失败:', error)
    Message.error('存储桶创建失败')
  }
}

// 下载文件
const downloadFile = async (file) => {
  try {
    console.log(`📥 下载文件: ${file.name}`)
    const url = `${API_BASE_URL}/files/download/${selectedBucket.value}/${file.name}`
    const link = document.createElement('a')
    link.href = url
    link.download = file.name
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (error) {
    console.error('❌ 文件下载失败:', error)
    Message.error('文件下载失败')
  }
}

// 获取预签名URL
const getPresignedUrl = async (file) => {
  try {
    console.log(`🔗 获取预签名URL: ${file.name}`)
    const data = await apiCall(`/files/presigned-url/${selectedBucket.value}/${file.name}`)
    selectedFile.value = file
    presignedUrl.value = data.url
    showUrlModal.value = true
  } catch (error) {
    console.error('❌ 获取访问链接失败:', error)
    Message.error('获取访问链接失败')
  }
}

// 删除文件
const deleteFile = async (file) => {
  try {
    console.log(`🗑️ 删除文件: ${file.name}`)
    await apiCall(`/files/${selectedBucket.value}/${file.name}`, {
      method: 'DELETE'
    })
    
    Message.success('文件删除成功')
    refreshFileList()
  } catch (error) {
    console.error('❌ 文件删除失败:', error)
    Message.error('文件删除失败')
  }
}

// 组件挂载时初始化
onMounted(() => {
  console.log('🚀 SourceData 组件初始化')
  fetchBuckets()
  fetchFiles(selectedBucket.value)
})
</script>

<style scoped>
.source-data-page {
  padding: 24px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  background: white;
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1d2129;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.content-container {
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.bucket-selector {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 24px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.file-list-container {
  margin-top: 24px;
}

.file-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e9ecef;
}

.file-list-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #1d2129;
}

.file-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.file-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 16px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.file-item:hover {
  background: #e9ecef;
  border-color: #dee2e6;
}

.file-icon {
  font-size: 24px;
  margin-right: 16px;
  width: 40px;
  text-align: center;
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-size: 14px;
  font-weight: 500;
  color: #1d2129;
  margin-bottom: 4px;
  word-break: break-all;
}

.file-meta {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #666;
}

.file-meta span {
  white-space: nowrap;
}

.file-actions {
  display: flex;
  gap: 4px;
  margin-left: 16px;
}

.empty-state {
  text-align: center;
  color: #666;
  padding: 48px 24px;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
}

.empty-state h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #1d2129;
}

.empty-state p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

/* 上传区域样式 */
.upload-container {
  padding: 16px 0;
}

.upload-area {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  padding: 40px 20px;
  text-align: center;
  background: #fafafa;
  transition: all 0.3s ease;
  cursor: pointer;
}

.upload-area:hover {
  border-color: #1890ff;
  background: #f0f8ff;
}

.upload-content {
  pointer-events: none;
}

.upload-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.upload-text {
  font-size: 16px;
  color: #1d2129;
  margin-bottom: 8px;
}

.upload-hint {
  font-size: 12px;
  color: #666;
}

.selected-files {
  margin: 16px 0;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.selected-files h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #1d2129;
}

.selected-file-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  background: white;
  border: 1px solid #e9ecef;
  border-radius: 4px;
  margin-bottom: 8px;
}

.selected-file-item:last-child {
  margin-bottom: 0;
}

.file-name {
  font-size: 14px;
  color: #1d2129;
  flex: 1;
  margin-right: 8px;
}

.file-size {
  font-size: 12px;
  color: #666;
  margin-right: 8px;
}

.upload-options {
  margin-top: 16px;
}

.upload-options label {
  font-size: 14px;
  color: #1d2129;
  font-weight: 500;
}

/* 模态框样式 */
.url-container p {
  margin-bottom: 12px;
}

.url-hint {
  font-size: 12px;
  color: #666;
  margin-top: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .file-list-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .file-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .file-actions {
    margin-left: 0;
    align-self: flex-end;
  }
  
  .file-meta {
    flex-direction: column;
    gap: 4px;
  }
}
</style>